const Roter=require('koa-router');
const {koaBody} = require('koa-body');
const path = require("path");
const fs = require("fs");
const { getUserList,login,upexcel,adduser,uploadavator,
  verifyusername,verifymobile,delUserByID,updateUser,getUserByID,
  addUserRoles,getUserRoles,changePWD,addUserPerms,getUserPerms,getUsersBydeptID} =require('../controller/user.controller')
const {userValidator,authToken,pwdCrypted,userNameMobileValidator } = require('../middleware/user.middleware')
const {avatorUploadDir} =require("../app/errorhandle")

const userRouter = new Roter({
  prefix: '/user'
});

userRouter.post('/login', userValidator,login)

userRouter.get('/', authToken,getUserList)
userRouter.get('/:id', authToken,getUserByID)
userRouter.delete('/:id', authToken,delUserByID)
userRouter.post('/', authToken,userNameMobileValidator,adduser)
userRouter.put('/', authToken,updateUser)
userRouter.post('/getUsersBydeptID', authToken,getUsersBydeptID)




userRouter.post('/upexcel', upexcel)

userRouter.post('/updateavator',authToken,
                koaBody({
                  multipart: true, // 支持多文件上传
                  // formLimit:"10mb",
                  // jsonLimit:"10mb",
                  // encoding: "gzip", // 编码格式
                  formidable: {
                    uploadDir: avatorUploadDir, // 设置文件上传目录
                    keepExtensions: true, // 保持文件的后缀
                    maxFieldsSize: 3 * 1024 * 1024, // 文件上传大小限制
                    onFileBegin: (name, file) => {
                      //console.log("onFileBegin:",file)
                      // 无论是多文件还是单文件上传都会重复调用此函数
                      // 最终要保存到的文件夹目录
                      //const dirName = format(new Date(), "yyyyMMddhhmmss");
                      //const dir = path.join(__dirname, `public/upload/${dirName}`);
                      const dir = avatorUploadDir;
                      //console.log(process.cwd());//process.cwd()获取node的工作目录
                      //console.log(dir);
                      // 检查文件夹是否存在如果不存在则新建文件夹
                      if (!fs.existsSync(dir)) {
                          fs.mkdirSync(dir);
                        }
                      // 文件名称去掉特殊字符但保留原始文件名称
                      //console.log('filename:',file.name)
                      const fileName = file.originalFilename
                        .replaceAll(" ", "_")
                        .replace(/[`~!@#$%^&*()|\-=?;:'",<>\{\}\\\/]/gi, "_");
                      file.originalFilename = fileName;
                      //file.newFilename=fileName
                      // 覆盖文件存放的完整路径(保留原始名称)
                      file.path = `${dir}/${fileName}`;
                      //console.log("file.path",file.path)
                    },
                    onError: (error) => {
                      //app.status = 400;
                      //log4js.error(error);
                      // 这里可以定义自己的返回内容
                      app.body = { 
                        success:false, //response成功标识
                        code:200,
                        message:error.message,
                        data:error.message
                      };
                      return;
                    },
                  },
                }),
                uploadavator)


userRouter.post('/verifyUserName',authToken,verifyusername)
userRouter.post('/verifyMobile',authToken,verifymobile)
userRouter.post('/getUserRoles',authToken,getUserRoles)
userRouter.post('/saveUserRoles',authToken,addUserRoles)
userRouter.post('/changePWD',authToken,pwdCrypted,changePWD)
userRouter.post('/addUserPerms',authToken,addUserPerms)
userRouter.post('/getUserPerms',authToken,getUserPerms)

module.exports = userRouter;